package com.sky.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.service.user.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private MerchantMapper merchantMapper;
    private final static String URL = "https://api.weixin.qq.com/sns/jscode2session";
    @Value("${sky.wechat.appid}")
    private String appId;
    @Value("${sky.wechat.secret}")
    private String secret;
    @Override
    public UserLoginVO userLogin(UserLoginDTO userLoginDTO) {
        String openId = getOpenId(userLoginDTO.getCode());
        if (!StringUtils.hasText(openId)){
            throw new BaseException("获取用户信息失败");
        }
        User user = userMapper.queryByOpenId(openId);
        if (user == null){
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        //生成token
        Map<String, Object> param = new HashMap<>();
        param.put("openId", openId);
        param.put("userId", user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),param);
        log.info("用户登录token:"+token);
        Merchant merchant = merchantMapper.queryByMerchantId(1);
        String merchantLocation = MapUtils.addressToLnglat(userLoginDTO.getLocation());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(merchantLocation, userLoginDTO.getLocation());

        UserLoginVO userLoginVO = UserLoginVO.builder().token(token)
                .shopAddress("精诚国际")
                .deliveryFee(delivoryCost)
                .shopId(merchant.getId())
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .openid(openId)
                .build();
        return userLoginVO;
    }

    /**
     * 获取openid
     */
    private String getOpenId(String code){
        Map<String,String> param = new HashMap<>();
        param.put("appid", appId);
        param.put("secret", secret);
        param.put("js_code", code);
        param.put("grand_type", "authorization_code");
        String response = HttpClientUtil.doGet(URL, param);
        log.info("微信登录返回"+response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        String openid = (String) jsonObject.get("openid");
        return openid;
    }

}
